package com.example.studyFile.jdknewfeatures._01_CompletableFuture_supplyAsync;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池
 *
 * @author zkmac on 2019/4/28.
 */
@Slf4j
public class ThreadPoolManagerTwo {

    private ThreadPoolManagerTwo() {

    }

    /**
     * 设置核心池大小
     */
    private static int corePoolSize = 10;

    /**
     * 设置线程池最大能接受多少线程
     */
    private static int maxPoolSize = 100;

    /**
     * 当前线程数大于corePoolSize、小于maximumPoolSize时，超出corePoolSize的线程数的生命周期
     */
    private static long keepAliveTime = 300L;

    /**
     * 队列容量
     */
    private static int capacity = 1000;

    /**
     * 设置时间单位，秒
     */
    private static TimeUnit timeUnit = TimeUnit.SECONDS;

    /**
     * 排队策略 放入队列
     */
    private static LinkedBlockingDeque<Runnable> linkedBlockingDeque = new LinkedBlockingDeque<>(capacity);


    /**
     * 定义线程池的名称
     */
    public static final ThreadFactory NAMED_THREAD_FACTORY = new ThreadFactoryBuilder()
            .setNameFormat("o2o-marketing-tool-product-two-%d").build();
    /**
     * 创建线程池
     */
    public static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
            corePoolSize,
            maxPoolSize,
            keepAliveTime,
            timeUnit,
            linkedBlockingDeque,
            NAMED_THREAD_FACTORY,
            (r, e) -> {
                log.info("o2o-marketing-tool-product-two queueFull");
                if (!e.isShutdown()) {
                    e.getQueue().poll();
                    e.execute(r);
                }
            });
}